//
//  NSString+Check.m
//  WashCar
//
//  Created by hehewyp on 15/8/25.
//  Copyright (c) 2015年 zm. All rights reserved.
//

#import "NSString+WYPExt.h"
#import <CommonCrypto/CommonDigest.h>

#define phonePredicate @"^[0-9]{11}$" // 手机号码
#define dianhuaPredicate @"^[0-9]{7,8}$" // 电话号码
#define passwordRegex @"^[A-Za-z0-9_.]{6,10}$" // 字母、数字、下划线、点，6-10位
#define nameRegex @"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w_]{1,56}$" // 中文，数字，字母，1-56位
#define verificationcodePredicate @"^[0-9]{6}$" // 验证码 数字，6位
#define emailPredicate @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
#define postPredicate @"^[1-9][0-9]{5}$";// 中国邮政编码正则
#define urlPredicate @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";//url正则

@implementation NSString (Check)

- (BOOL)isValidPhoneNum {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phonePredicate];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isValidDianHuaNum {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", dianhuaPredicate];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isValidPassword {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passwordRegex];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isValidName {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isVaildVerificationCode {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", verificationcodePredicate];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isVaildEmail {
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailPredicate];
    
    return [pred evaluateWithObject:self];
}

- (BOOL)isVaildUrl
{
    NSString * regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSPredicate * pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:self];
}

@end

@implementation NSString (md5)

-(NSString *)md5 { // 32位小写
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

@end

@implementation NSString (TextFieldText)

// 调用textField(textField: UITextField, shouldChangeCharactersInRange时，
// 第一个输入的字符不会进入前面一个方法，此方法就是将第一个字符插入[futureString insertString:string atIndex:range.location]

- (NSString *) changeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSMutableString * futureString = [NSMutableString stringWithString:self];
    if (range.length == 0) {
        [futureString insertString:string atIndex:range.location];
    } else {
        [futureString deleteCharactersInRange:range];
    }
    
    return futureString;
}

@end

@implementation NSString (bounding)

- (CGFloat) boundingHeightWithSize:(CGSize)size font:(UIFont *) font lineSpace:(CGFloat) lineSpace {
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.lineSpacing = lineSpace;
    NSDictionary *attributes = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paragraphStyle};
    CGRect rect = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    return rect.size.height;
}

@end

@implementation NSString (html)

- (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}

@end

@implementation NSString (json)

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

+ (NSString*)DataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"转字符串失败 an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

@end

@implementation NSString (date)

+ (NSString *)converToDateString:(NSTimeInterval)time formatter:(NSString *) format; {
    NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate: detaildate];
    return currentDateStr;
}

@end

